package com.nxj.sqlSession;

import com.nxj.config.BoundSql;
import com.nxj.pojo.Configuration;
import com.nxj.pojo.MappedStatement;
import com.nxj.utils.GenericTokenParser;
import com.nxj.utils.ParameterMapping;
import com.nxj.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {

    public Connection connection;

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        connection = configuration.getDataSource().getConnection();
        BoundSql boundSql = getBoundSql(mappedStatement.getSql());
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        Class<?> parameterTypeClass = mappedStatement.getParamterType();

        List<ParameterMapping> parameterMappings = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            Field declaredField = parameterTypeClass.getDeclaredField(parameterMapping.getContent());
            declaredField.setAccessible(true);

            preparedStatement.setObject(i + 1, declaredField.get(params[0]));
        }

        ResultSet resultSet = preparedStatement.executeQuery();
        Class<?> resultTypeClass = mappedStatement.getResultType();
        ArrayList<Object> objects = new ArrayList<>();
        while (resultSet.next()) {
            Object returnBean = resultTypeClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++)
                new PropertyDescriptor(metaData.getColumnName(i), resultTypeClass).getWriteMethod().invoke(returnBean, resultSet.getObject(metaData.getColumnName(i)));

            objects.add(returnBean);
        }
        return (List<E>) objects;
    }

    @Override
    public <E> E queryForObject(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        List list = query(configuration, mappedStatement, params);
        if (list == null || list.size() < 1) {
            return null;
        }
        return (E) list.get(0);
    }

    @Override
    public boolean insertOneObject(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        connection = configuration.getDataSource().getConnection();
        BoundSql boundSql = getBoundSql(mappedStatement.getSql());
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        Class<?> parameterTypeClass = mappedStatement.getParamterType();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            Field declaredField = parameterTypeClass.getDeclaredField(parameterMapping.getContent());
            declaredField.setAccessible(true);
            preparedStatement.setObject(i + 1, declaredField.get(params[0]));
        }

        return preparedStatement.execute();
    }

    @Override
    public boolean deleteByCondition(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        connection = configuration.getDataSource().getConnection();
        BoundSql boundSql = getBoundSql(mappedStatement.getSql());
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        Class<?> parameterTypeClass = mappedStatement.getParamterType();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            Field declaredField = parameterTypeClass.getDeclaredField(parameterMapping.getContent());
            declaredField.setAccessible(true);
            preparedStatement.setObject(i + 1, declaredField.get(params[0]));
        }

        return preparedStatement.execute();
    }

    @Override
    public int updateByCondition(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        connection = configuration.getDataSource().getConnection();
        BoundSql boundSql = getBoundSql(mappedStatement.getSql());
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        Class<?> parameterTypeClass = mappedStatement.getParamterType();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            Field declaredField = parameterTypeClass.getDeclaredField(parameterMapping.getContent());
            declaredField.setAccessible(true);
            preparedStatement.setObject(i + 1, declaredField.get(params[0]));
        }

        return preparedStatement.executeUpdate();
    }

    @Override
    public void close() throws Exception {
        connection.close();
    }

    /**
     * 完成对#{}的解析工作：1.将#{}使用？进行代替，2.解析出#{}里面的值进行存储
     *
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        //标记处理类：配置标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的sql
        String parseSql = genericTokenParser.parse(sql);
        //#{}里面解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        return new BoundSql(parseSql, parameterMappings);
    }

}
